import {Dialog} from "@lowcode/jpaas-common-lib";


export default {
    methods:{
        i18n_(name, text, key) {
            return this.$ti18(name, text, "formCustom", key);
        },
        handInsertScript(item){
            this[item.clickEvent]();
        },
        insertScript(script){
            this.$refs.jsScriptEditor.insertContent(script);
        },
        insertFormWindow(){
            let script=`
                let conf={
                title:${this.$ti18('title','表单标题','insertScript')},
               alias:${this.$ti18('alias','表单方案别名','insertScript')},
               pkId:${this.$ti18('pkId','主键','insertScript')},
               readOnly:true,
               max:true
           }
           this.openFormSolution(conf);`;
            this.$refs.jsScriptEditor.insertContent(script);
        },
        insertFormWindowOpen(){
            let script=`
                let conf={
                    formAlias:${this.$ti18('alias','表单方案别名','insertScript')},
                    pkId:${this.$ti18('pkId','主键','insertScript')},
                    readOnly:true
                };
                this.openWindowUrl(conf);`;
            this.$refs.jsScriptEditor.insertContent(script);
        },
        insertFormUrl(){
            let script=`
                let conf={
            formAlias:${this.$ti18('alias','表单方案别名','insertScript')},
            pkId:${this.$ti18('pkId','主键','insertScript')},
            readOnly:true
        };
        this.openFormUrl(conf);`;
            this.$refs.jsScriptEditor.insertContent(script);
        },
        insertFormList(){
            let script=`this.openList(`+this.$ti18('listAlias','列表别名','insertScript')+`)`;
            this.$refs.jsScriptEditor.insertContent(script);
        },
        insertOpenMenu(){
            let script=`
             let conf={
                 title:"菜单名称",
                 key:"菜单key",
                 //参数
                 params:{
                     //主键
                    pkId:"主键",
                    //使用只读方式打开
                    readOnly:true
                }
            };
            this.openTabs(conf);`;
            this.$refs.jsScriptEditor.insertContent(script);
        },
        insertInvokePcScript() {
            var self_ = this;
            this.insertInvokeScript(function (script) {
                self_.$refs.jsScriptEditor.insertContent(script);
            })
        },
        //插入打开页面定制函数
        addOpenCustomPage(){
            let self_=this;
            var config={
                curVm: this, widthHeight: ['900px', '600px'],
            };
            Dialog.openCustomPageDialog(config,(res)=>{
                let json={};
                let paramDef=res.params || "[]";
                let paramsAry=JSON.parse(paramDef);
                for(let i=0;i<paramsAry.length;i++){
                    let o=paramsAry[i];
                    json[o.value]=o.label;
                }
                let str=JSON.stringify(json);

                let script=`/**
                     * @param alias ${self_.i18n_('script.alias', '别名')}
                     * @param params ${self_.i18n_('list.paraConfig', '传入参数')}
                      * config:{max:true,shade:true,width:200,height:200}
                     * @param title ${self_.i18n_('script.dialogName', '对话框名称')}
                     * @param callback ${self_.i18n_('script.callback', '回调函数')}
                     */
                let params=${str};
                this.openCustomView("${res.alias}",params,"${res.name}",{max:true,shade:true,width:200,height:200,appId:"${res.appId}"},function(action,data){
                console.log(data)
                })`;
                self_.$refs.jsScriptEditor.insertContent(script);
            });
        },
        insertInvokeScript(callback) {
            Dialog.openInvokeScriptDialog({
                curVm: this,
                widthHeight: ['800px', '600px']
            }, function (self, data) {
                var ary = JSON.parse(data.params);
                var paramValue = self.getParamValue(ary, false);
                var tmp = paramValue.tmp;
                var strTmp = paramValue.strTmp;
                let isSuccess = self.$ti18('isSuccess','是否执行成功','insertScript');
                let message = self.$ti18('message','提示信息','insertScript');
                let scriptReturnData = self.$ti18('scriptReturnData','脚本返回数据','insertScript');
                var str = "/**\n" +
                    strTmp +
                    " * @return " + data.descp + "\n" +
                    " */\n";
                if (data.async) {
                    str += "this.invokeScript(\"" + data.alias + "\"," + JSON.stringify(tmp) + ",function(data){\n";
                    str += "   //data:{success:"+isSuccess+",message:"+message+",data:"+scriptReturnData+"}\n";
                    str += "});"
                } else {
                    str += "//rtn:{success:"+isSuccess+",message:"+message+",data:"+scriptReturnData+"}\n";
                    str += "var rtn= this.invokeScriptPromise(\"" + data.alias + "\"," + JSON.stringify(tmp) + ");";
                }
                if (callback) {
                    callback(str);
                }
            })
        },
        insertPcCustomQuery() {
            var self_ = this;
            this.insertCustomQuery(function (script) {
                self_.$refs.jsScriptEditor.insertContent(script);
            })
        },
        insertCustomQuery(callback) {
            Dialog.openCustomDataDialog({
                curVm: this,
                widthHeight: ['800px', '600px']
            }, function (self, data) {
                var whereField = self.getWhereField(JSON.parse(data.whereField));
                var resultField = self.getResultField(JSON.parse(data.resultField));
                let returnData = self.$ti18('returnData','返回的数据','insertScript');
                var str = "\n/**\n" +
                    whereField.strTmp +
                    " */ \n" +
                    "this.invokeCustomQuery(\"" + data.key + "\"," + JSON.stringify(whereField.tmp) + ",function(data){\n" +
                    "   //" + returnData + " data:[" + resultField + "]\n" +
                    "});";

                if (callback) {
                    callback(str);
                }

            });
        },
        getInterfaceParams(rootParams,key,name,paramsStr,isJson){
            var params=JSON.parse(paramsStr);
            if(isJson){
                var getParams=function(array) {
                    return array.filter(function (item) {
                        if (item.paramType == 'object' || item.paramType == 'array') {
                            item.children = getParams(item.children);
                            return item.children.length>0;
                        } else {
                            return item.paramSource == 'param';
                        }
                    })
                }
                let filterArr = getParams(params);
                if (filterArr.length > 0) {
                    var getParamsValue=function(obj){
                        if (obj.paramType == 'object') {
                            var paramsValue={};
                            for(var i=0;i<obj.children.length;i++){
                                var item=obj.children[i];
                                paramsValue[item.paramName]=getParamsValue(item);
                            }
                            return paramsValue;
                        } else if(obj.paramType == 'array') {
                            var paramsValue=[];
                            for(var i=0;i<obj.children.length;i++){
                                var item=obj.children[i];
                                paramsValue.push(getParamsValue(item));
                            }
                            return paramsValue;
                        } else {
                            if(obj.paramType == 'number'){
                                return 0;
                            }else if(obj.paramType == 'boolean'){
                                return false;
                            }else{
                                return "";
                            }
                        }
                    }
                    rootParams[key] = getParamsValue(filterArr[0]);
                    return " @param "+key+" "+name+"\n";
                }
            }else{
                let filterArr = params.filter(item => item.paramSource == 'param');
                if (filterArr.length > 0) {
                    rootParams[key]={};
                    filterArr.map(item=>{
                        rootParams[key][item.paramName]="";
                    });
                    return " @param "+key+" "+name+"\n";
                }
            }
            return "";
        },
        insertInvokePcInterface() {
            var self_ = this;
            this.insertInvokeInterface(function (script) {
                self_.$refs.jsScriptEditor.insertContent(script);
            })
        },
        insertInvokeInterface(callback) {
            Dialog.openSysInterfaceDialog({
                curVm: this, max: true
            }, function (self, data) {
                let bodys = self.$ti18('bodys','请求体','insertScript');
                let headers = self.$ti18('headers','请求头','insertScript');
                let pathParams = self.$ti18('pathParams','路径参数','insertScript');
                let querys = self.$ti18('querys','查询参数','insertScript');
                let apiReturn = self.$ti18('apiReturn','接口返回数据','insertScript');
                let apiName = self.$ti18('apiName','接口名称','insertScript');
                let apiPath = self.$ti18('apiPath','接口路径','insertScript');

                var params = {};
                var strTmp = "";
                if ((data.apiDataType == 'form' || data.apiDataType == 'json') && data.apiBody) {
                    //请求体参数配置
                    strTmp += self.getInterfaceParams(params, 'bodys', bodys, data.apiBody, data.apiDataType == 'json');
                }
                if (data.apiHeaders) {
                    //请求头参数配置
                    strTmp += self.getInterfaceParams(params, 'headers', headers, data.apiHeaders, false);
                }
                if (data.apiPathParams) {
                    //请求路径参数配置
                    strTmp += self.getInterfaceParams(params, 'pathParams', pathParams, data.apiPathParams, false);
                }
                if (data.apiQuery) {
                    //查询参数配置
                    strTmp += self.getInterfaceParams(params, 'querys', querys, data.apiQuery, false);
                }
                var str = "\n/**\n" +
                    apiName + data.apiName + "\n" +
                    apiPath + data.apiPath + "\n" +
                    strTmp +
                    " */ \n" +
                    "this.invokeInterface(\"" + (data.apiKey || data.apiId) + "\"," + JSON.stringify(params) + ",function(data){\n" +
                    "   //data:"+apiReturn+"\n" +
                    "});";
                if (callback) {
                    callback(str);
                }
            })
        },
        //获取自定义查询返回字段
        getResultField(ary) {
            var str = "{";
            for (var i = 0; ary && i < ary.length; i++) {
                if (i > 0) {
                    str += ",";
                }
                var obj = ary[i];
                str += obj.fieldName;
            }
            str += "}";
            return str;
        },
        //获取自定义查询条件字段
        getWhereField(ary) {
            var tmp = {};
            var strTmp = " * @param ";
            for (var i = 0; ary && i < ary.length; i++) {
                var obj = ary[i];
                var paramType = obj.columnType;
                strTmp += obj.fieldName + " " + paramType + "\n";
                tmp[obj.fieldName] = "";
            }
            return {
                tmp: tmp,
                strTmp: strTmp
            };
        },
        getParamValue(ary, isChild) {
            var tmp = {};
            var strTmp = "";
            for (var i = 0; ary && i < ary.length; i++) {
                var obj = ary[i];
                var paramType = obj.paramType;
                if (isChild) {
                    strTmp += " *  @subParam ";
                } else {
                    strTmp += " * @param ";
                }
                strTmp += obj.paramName + " " + obj.paramDescp + " " + obj.paramType + "\n";
                if (!paramType || paramType == 'string') {
                    tmp[obj.paramName] = "";
                } else if (paramType == 'int') {
                    tmp[obj.paramName] = 0;
                } else if (paramType == 'date') {
                    tmp[obj.paramName] = null;
                } else if (paramType == 'boolean') {
                    tmp[obj.paramName] = false;
                } else if (paramType == 'obj') {
                    var child = obj.children;
                    var paramValue = this.getParamValue(child, true);
                    tmp[obj.paramName] = paramValue.tmp;
                    strTmp += paramValue.strTmp;
                }
            }
            return {
                tmp: tmp,
                strTmp: strTmp
            };
        },
        //插入ajax
        insertAjax(){
            this.$refs.jsScriptEditor.insertContent("/**\n" +
                "         * get(url)、postJson(url,params)、postForm(url,params)\n" +
                "         */\n" +
                "        this.getAjax()");
        }
    }
}